import { Select } from "antd";
import type { SelectProps } from 'antd';
import { useComponentsStore, getComponentById } from "@/stores/edit-pages-store";
import { useEffect, useMemo, useState } from "react";
import { axiosInstance } from "@/interfaces";
import { InfoCircleFilled } from "@ant-design/icons";
export function ApiFieldSelector(props: { onChange?: Function, mode?: SelectProps["mode"]}) {
  const { onChange, mode } = props;
  const { curComponent, schema, curComponentId } = useComponentsStore();
  const [options, setOptions] = useState([]);
  const [showIcon, setShowIcon] = useState(false);

  const api = curComponent?.props?.api;
  // const originApi = useMemo(()=>{
  //   const cName = curComponent?.name
  //   if(cName === "Table"){
  //     return curComponent?.props?.api;
  //   }else if(cName === "TableColumn"){
  //     const parentId = curComponent?.parentId
  //     const tableComponent = getComponentById(parentId, schema)
  //     return tableComponent?.props?.api
  //   }
  // },[curComponentId])
  useEffect(() => {
    if (api && api.url) {
      getFields();
    }
  }, [api]);

  async function getFields() {
    const { url } = api;
    const res = await axiosInstance.get(url, {
      params: { page: 1, size: 1, filter: "", dev: true },
    });
    if (res) {
      setShowIcon(true);
      const { fields } = res.data;
      setOptions(fields);
    } else {
      setShowIcon(false);
      setOptions([]);
    }
  }
  function handleChange(val: string[]) {
    onChange?.(val);
  }
  return (
    <div className="flex justify-between gap-x-2">
      <Select mode={mode} onChange={handleChange} options={options}/>
      {!showIcon && <InfoCircleFilled style={{ color: "orange" }} title="请设置正确的api" />}
    </div>
  );
}
